package com.peak.distribution.jms.sms;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.peak.distribution.entity.admin.DisSmsLog;
import com.peak.distribution.entity.agent.DisAgent;
import com.peak.distribution.enums.SmsType;
import com.peak.distribution.manager.admin.DisSmsLogManager;
import com.peak.distribution.manager.agent.DisAgentManager;
import com.peak.distribution.tools.AliyunSmsTools;
import com.peak.spring.boot.core.mapper.JsonMapper;
import com.peak.spring.boot.tools.Converts;
import com.peak.spring.boot.tools.Dates;
import com.peak.spring.boot.tools.Emptys;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Transactional
public class SmsConsumer {
	
	@Autowired
	private DisSmsLogManager smsLogManager;
	
	@Autowired
	private DisAgentManager agentManager;
	
	@Autowired
	private AliyunSmsTools aliyunSmsTools;
	
	/**
	 * 接收发送短信的消费者
	 * @param json
	 */
	@JmsListener(destination = "${mq.queue.sms.send}")
	public void send(String json) {
		log.info("接收发送短信消息：{}", json);
		// 转换消息
		JsonMapper jsonMapper = JsonMapper.nonDefaultMapper();
		Map<String, Object> map = jsonMapper.fromJson(json, HashMap.class, String.class, Object.class);
		// 得到手机号码
		String mobileNos = StringUtils.trim(Converts.toString(map.get("mobileNos")));
		String templateCode = Converts.toString(map.get("templateCode"));
		try {
			SendSmsResponse response = aliyunSmsTools.sendSms(mobileNos, templateCode, Converts.toString(map.get("content")));
			log.info("短信已发送至：{}, 任务内容：{}", mobileNos, jsonMapper.toJson(response));
			String bizId = "-1";
			if (response.getCode() != null && response.getCode().equals("OK")) {
				bizId = response.getBizId();
			}
			saveLog(map, bizId);
		} catch (ClientException e) {
			log.info("短信发送失败", e);
		}
	}
	
	/**
	 * 保存短信发送的日志
	 * @param map 参数
	 * @param response 短信网关返回的结果
	 */
	public void saveLog(Map<String, Object> map, String bizId) {
		DisSmsLog smsLog = new DisSmsLog();
		// 代理商发送的短信需要把代理商记录下来
		String agentId = Converts.toString(map.get("agentId"));
		if (Emptys.isNotEmpty(agentId)) {
			DisAgent agent = agentManager.getOne(Converts.toInteger(agentId));
			smsLog.setFrom(agent.getUser());
		}
		// 把数据进行设置
		smsLog.setMobileNos(Converts.toString(map.get("mobileNos")));
		smsLog.setContent(Converts.toString(map.get("content")));
		smsLog.setSendTime(Dates.now());
		smsLog.setType(SmsType.valueOf(Converts.toString(map.get("type"))));
		smsLog.setResult(bizId);// 根据流水号可以去查询短信
		smsLogManager.save(smsLog);
	}

}
